const http = require('http')
const parse = require('url').parse
const path = require('path')
const fs = require('fs')
const mime = require('mime')

// 访问 http://localhost:3000/dir/index.html

const server = http.createServer((req, res) => {
    //  1.路径解析
    let { pathname, query } = parse(req.url, true)
    pathname = decodeURIComponent(pathname) // 中文会被编码
    let abPath = path.join(__dirname,pathname)
    console.log(abPath)
    // 2.状态处理（文件还是目录）
    fs.stat(abPath,(err,staObj)=>{
        if(err){
            res.statusCode = 404
            res.end('Not Found')
            return
        }
        if(staObj.isFile()){
            fs.readFile(abPath,(err,data)=>{
                res.setHeader('content-type', mime.getType(abPath)+';charset=utf8')
                res.end(data)
            })
            return
        }
        fs.readFile(path.join(abPath,'index.html'),(err,data)=>{
            res.setHeader('content-type', mime.getType(abPath)+';charset=utf8')
            res.end(data)
        })
    })
})
server.listen(3000)
